package projectg06.hclinicas;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class OutFileManager {
	private File root;
	private File outDir;
	private File inDir;
	private List <Prueba> tests;

	public File getRoot() {
		return root;
	}

	public void setRoot(File root) {
		this.root = root;
		if(root!=null&&root.exists()){
		  inDir=new File(root.getPath()+"\\IN");
		  inDir.mkdirs();
		  outDir=new File(root.getPath()+"\\OUT");
		  outDir.mkdirs();
		}else {
			inDir=null;
			outDir=null;
		}
	}

	public void setTests(List<Prueba> tests) {
		this.tests = tests;
	}
	
	public OutFileManager(File file, List<Prueba> lista) {
		setRoot(file);
		this.tests=lista;
	}

	public void generarListFlle() throws Exception {
		if(root==null){
			throw new Exception("No se ha seteado bien el root");
		}
		Iterator<Prueba> it =tests.iterator();
		BufferedWriter sw=new BufferedWriter(new FileWriter(root.getPath()+"\\LOTE_DE_PRUEBAS.LIST"));
		while(it.hasNext()){
			sw.write(inDir.getPath()+"\\"+it.next().getNombre()+".IN\r\n");
		}
		sw.close();
	}

	public void generarOutFiles() throws Exception {
		if(outDir==null){
			throw new Exception("No se ha seteado bien el root");
		}
		Iterator<Prueba> it =tests.iterator();
		Prueba p;
		while(it.hasNext()){
			p=it.next();
			BufferedWriter sw=new BufferedWriter(new FileWriter(outDir.getPath()+"\\"+p.getNombre()+".OUT"));
			sw.write(p.getOut().trim());
			sw.close();
		}
	}

	public void generarInFlles() throws Exception {
		if(inDir==null){
			throw new Exception("No se ha seteado bien el root");
		}
		Iterator<Prueba> it =tests.iterator();
		Prueba p;
		while(it.hasNext()){
			p=it.next();
			BufferedWriter sw=new BufferedWriter(new FileWriter(inDir.getPath()+"\\"+p.getNombre()+".IN"));
			sw.write(p.getIn().trim());
			sw.close();
		}
	}
	@Override
	public String toString() {
		Iterator it=tests.iterator();
		StringBuffer sb=new StringBuffer();
		while(it.hasNext()){
			sb.append(it.next()).append("\r\n");
		}
		return sb.toString();
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		List<Prueba> list=new ArrayList<Prueba>();
		list.add(new Prueba("001_p1","texto1","salida1"));
		list.add(new Prueba("002_p2","texto2","salida2"));
		list.add(new Prueba("003_p3","texto3","salida3"));
		list.add(new Prueba("004_p4","texto4","salida4"));
		OutFileManager ofm=new OutFileManager(new File("."),list);
		System.out.println(ofm);
		ofm.generarInFlles();
		ofm.generarOutFiles();
		ofm.generarListFlle();

	}


}
